<template>
    <div class="login-modal-dialog">
        <div class="login-modal-dialog__mask" :class="{ 'mask__blur': isBlur }"></div>
        <div class="login-modal-dialog__content">
            <div class="icon-back" @click="onBack" v-if="isBack">
                <el-icon :size="24" color="#333">
                    <ArrowLeft></ArrowLeft>
                </el-icon>
            </div>

            <div class="icon-close" @click="onClose" v-if="isClose">
                <img :src="`${_oss_}images/icon-close-default.png`" />
            </div>

            <div class="login-modal-dialog__title">
                {{ modalTitle }}
            </div>

            <div class="login-form">
                <el-input type="text" size="large" v-model="form.phone" placeholder="请输入你的手机号" @keyup.enter="onSubmit">
                    <template #prepend>
                        <el-select v-model="num" size="large" style="width: 80px">
                            <el-option label="+86" :value="86" />
                        </el-select>
                    </template>
                </el-input>

                <el-input type="text" size="large" v-model="form.code" placeholder="请输入验证码" style="margin-top: 20px"
                    v-if="type === 2" @keyup.enter="onSubmit">
                    <template #append>
                        <el-button @click="onSendCode">{{
                            codeText
                        }}</el-button>
                    </template>
                </el-input>

                <el-input type="password" size="large" v-model="form.password" placeholder="请输入密码" style="margin-top: 20px"
                    v-if="type === 1" @keyup.enter="onSubmit" show-password>
                </el-input>


                <div class="form-footer" v-if="type === 1">
                    <div class="remember-password">
                        <el-checkbox v-model="rememberPassword" size="small">记住密码</el-checkbox>
                    </div>
                    <span class="forgot-pwd" @click="onForgetPwd">
                        忘记密码？
                    </span>
                </div>
            </div>


            <div class="login-btn" @click="onSubmit" :style="{ marginTop: '60px' }">
                登录
            </div>

            <div class="login-footer" :style="{ marginTop: '30px' }">
                <div class="btn-group" @click="toRegister">
                    <img :src="`${_oss_}images/login/register.png`" />
                    立即注册
                </div>

                <div class="btn-group" @click="onChangeType(1)" v-if="type !== 1">
                    <img :src="`${_oss_}images/login/password.png`" />
                    密码登录&emsp;
                </div>

                <div class="btn-group" @click="onChangeType(2)" v-if="type !== 2">
                    <img :src="`${_oss_}images/login/password.png`" />
                    验证码登录
                </div>
            </div>
        </div>
    </div>
</template>
<script setup>
import { ArrowLeft } from "@element-plus/icons-vue";
import {
    UserLogin,
    SendUserCode,
    UserLoginByCode,
    SetTaskScore,
    SetOnline,
} from "~/api";

const userStore = useUserStore();
const pageStore = usePageStore();
const type = ref(1);
const num = ref(86);

const props = defineProps({
    isBlur: {
        type: Boolean,
        default: false,
    },

    isBack: {
        type: Boolean,
        default: false,
    },

    isClose: {
        type: Boolean,
        default: true,
    },
    immediate: {
        type: Boolean,
        default: true,
    }
})

const router = useRouter();
const rememberPassword = ref(Object.keys(userStore.loginInfo).length !== 0);
const form = reactive({
    phone: userStore.loginInfo.phone || "",
    password: userStore.loginInfo.password || "",
    code: ""
});
const codeText = ref("获取验证码");
let codeMaxSecond = 0;
let codeInterval = null;

const emits = defineEmits(['close']);

const modalTitle = computed(
    () => ({ 1: "密码登录", 2: "欢迎登录" }[type.value])
);

const infoVerify = ({ phone, type, code, password, birthday }) => {
    if (isEmpty(phone)) {
        Message().warning("请输入手机号");
        return false;
    }

    if (!isPhone(phone)) {
        Message().warning("请输入正确的手机号");
        return false;
    }

    if (isEmpty(password)) {
        Message().warning("请输入密码");
        return false;
    }

    if (password.length < 6 || password.length > 16) {
        Message().warning("请输入6到16位密码");
        return false;
    }
    return true;
};

const onClose = () => {
    emits('close');
}

const onBack = () => {
    router.back(-1);
}

const LoginSuccess = async (res, callback) => {
    const pageStore = usePageStore();
    if (res.code == 200) {
        try {
            Message().success("登录成功");
            userStore.token = res.data.token;

            await GET_USERINFO();
            await GET_AVATAR();
            await GET_MIDNUM();

            if (process.env.NODE_ENV === "production") {
                SetOnline();
                timeExit();
            }

            HAS_NEW_MESSAGE();
            connectSocket();
            NoticeTips();

            onClose();

            setTimeout(() => {
                if (
                    pageStore.scoreParams &&
                    JSON.stringify(pageStore.scoreParams) !== "{}"
                ) {
                    SetTaskScore({
                        code: pageStore.scoreParams.code,
                        _id: pageStore.scoreParams._id,
                    });
                    pageStore.scoreParams = {};
                }

                // 跳转处理
                if (
                    pageStore.urlParams &&
                    JSON.stringify(pageStore.urlParams) !== "{}"
                ) {
                    let url = pageStore.urlParams.url;
                    let search = pageStore.urlParams.search || "";

                    if (pageStore.urlParams.params) {
                        if (pageStore.urlParams.params.includes("uid")) {
                            search +=
                                (search ? "&" : "") + "uid=" + res.data.id;
                        }
                    }

                    if (pageStore.urlParams.encrypt && search) {
                        search = aesEncrypt(search);
                    }

                    if (pageStore.isLoginOpen) {
                        navigateTo(url + (search ? "?" + search : ""), {
                            external: url.includes("http"),
                            replace: true,
                            open: true,
                        });
                    }
                }
            }, 200)

            typeof callback === "function" && callback(res);
        } catch (err) {
            Message().error(err);
        }
    } else {
        Message().error(res.msg);
    }
};

const onSendCodeSuccess = () => {
    const _func = () => {
        if (codeMaxSecond === 0) {
            codeText.value = "获取验证码";
            clearInterval(codeInterval);
        } else {
            codeText.value = `${codeMaxSecond--}s`;
        }
    };
    codeMaxSecond = 120;
    codeInterval = setInterval(_func, 1000);
    _func();
};

const onSendCode = async () => {
    if (codeMaxSecond > 0) return;
    if (isPhone(form.phone)) {
        const res = await SendUserCode({
            phone: form.phone,
            event: "login",
        });

        if (res.code == 200) {
            Message().success("发送成功");
            onSendCodeSuccess();
        } else {
            Message().error(res.msg);
        }
    } else {
        Message().warning("请输入正确的手机号");
    }
};

const onPwdLogin = async () => {
    const verify = infoVerify({
        phone: form.phone,
        type: type.value,
        code: form.code,
        password: form.password,
    });

    if (verify) {
        const res = await UserLogin({
            username: form.phone,
            password: form.password,
        });

        LoginSuccess(res, () => {
            if (rememberPassword.value) {
                userStore.SET_LOGININFO({
                    phone: form.phone,
                    password: form.password,
                });
            } else {
                userStore.SET_LOGININFO({});
            }
        });
    }
}

const onCodeLogin = async () => {
    if (isEmpty(form.phone)) {
        Message().warning("请输入手机号");
        return false;
    }

    if (!isPhone(form.phone)) {
        Message().warning("请输入正确的手机号");
        return false;
    }

    if (isEmpty(form.code)) {
        Message().warning("请输入验证码");
        return false;
    }

    const res = await UserLoginByCode({
        mobile: form.phone,
        code: form.code,
    });

    LoginSuccess(res);
};

const onSubmit = async () => {
    switch (type.value) {
        case 1:
            onPwdLogin();
            break;
        case 2:
            onCodeLogin();
            break;
        default:
            break;
    }
}

const onForgetPwd = () => {
    navigateTo("/forgetPwd", {
        open: "_blank",
    });
}

const toRegister = () => {
    navigateTo("/register.html", {
        open: "_blank",
    })
}

const onChangeType = (value) => {
    type.value = value;
}
</script>
<style lang="scss" scoped>
.mask__blur {
    backdrop-filter: blur(10px);
}

.login-modal-dialog {
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    height: 100vh;
    z-index: 1999;

    &__mask {
        position: relative;
        width: 100%;
        height: 100%;
        background-color: rgba($color: #000000, $alpha: 0.5);
    }

    &__content {
        background: #fff;
        border-radius: 10px;
        box-sizing: border-box;
        height: 400px;
        left: 50%;
        padding: 0 24px 0 26px;
        position: absolute;
        top: 50%;
        transform: translate(-50%, -50%);
        width: 350px;
    }

    .login-form {
        margin-top: 39px;
        position: relative;

        .form-footer {
            width: 100%;
            position: absolute;
            left: 0;
            bottom: -30px;
            display: flex;
            align-items: center;
            justify-content: space-between;

            .forgot-pwd {
                color: #5185fb;
                font-size: 12px;
                cursor: pointer;
                user-select: none;
            }
        }
    }

    .login-btn {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        height: 40px;
        font-size: 18px;
        color: #fff;
        background-color: #5185fb;
        border-radius: 6px;
        cursor: pointer;
        user-select: none;
    }

    .login-footer {
        display: flex;
        justify-content: center;
        margin-top: 30px;
        color: #666;
        font-size: 14px;

        .btn-group {
            display: flex;
            align-items: center;
            cursor: pointer;
            user-select: none;

            &:first-of-type {
                margin-right: 40px;
            }

            img {
                margin-right: 6px;
                color: #666;
                font-size: 14px;
            }
        }
    }

    &__title {
        text-align: center;
        margin-top: 39px;
        font-size: 30px;

    }

    .icon-back {
        display: flex;
        align-items: center;
        justify-content: center;

        position: absolute;
        top: -30px;
        left: -30px;
        width: 34px;
        height: 34px;
        background-color: #fff;
        border-radius: 50%;
        cursor: pointer;
    }

    .icon-close {
        display: flex;
        align-items: center;
        justify-content: center;

        position: absolute;
        top: -30px;
        right: -30px;
        width: 34px;
        height: 34px;
        background-color: #fff;
        border-radius: 50%;
        cursor: pointer;

        img {
            width: 14px;
            height: 14px;
        }
    }
}
</style>